//
//  VRMainViewController.m
//  VRKaiCai
//
//  Created by slh on 2017/6/23.
//  Copyright © 2017年 slh. All rights reserved.
//

#import "VRMainViewController.h"
#import "VRCaipiaoDetailViewController.h"

#import "VRCaipiaoClassCell.h"
#import "VRCaipiaoClass.h"

#import "NSString+Tools.h"

@interface VRMainViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) UISearchBar *searchBar;

@property (nonatomic, assign) BOOL isSearched;

@property (nonatomic, strong) NSMutableArray *classModelArray;

@property (nonatomic, strong) NSMutableArray *searchResultArr;


@end

@implementation VRMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"彩票类型";
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    
    self.classModelArray = [NSMutableArray array];
    self.searchResultArr = [NSMutableArray array];
    
    [self setupSubView];
    [self setupSearchBar];
    
    [self getCaipiaoClass];
}


- (void)setupSubView
{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}


//加载搜索框
-(void)setupSearchBar{
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    NSArray *subViews;
    subViews = [(searchBar.subviews[0]) subviews];
    for (id view in subViews)
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            UIButton* cancelbutton = (UIButton* )view;
            [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
            break;
        }
    }
    
    [searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
//    searchBar.showsCancelButton = YES;
    searchBar.tintColor = [UIColor grayColor];
    searchBar.frame = CGRectMake(0, 0, Screen_width, 44);
    [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex : 0] removeFromSuperview];
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.searchBar = searchBar;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, 44)];
    [view addSubview:searchBar];
    self.tableView.tableHeaderView = view;
    
}


#pragma mark - data
// 获取彩票类别
- (void)getCaipiaoClass
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"appkey"] = @"94cd7eb2aeb10bda";
    
    [manager GET:URL_CaiPiaoClass parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        VRLog(@"result:%@", responseObject);
        
        NSArray *array = responseObject[@"result"];
        
        for (NSDictionary *obj in array) {
            VRCaipiaoClass *item = [[VRCaipiaoClass alloc] init];
            [item setValuesForKeysWithDictionary:obj];
            
            [self.classModelArray addObject:item];
        }
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        VRLog(@"erro:%@", error);
    }];
}


#pragma mark - 工具方法
- (void)filterContentForSearchText:(NSString*)searchText
{
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    
    [self.searchResultArr removeAllObjects];
    for (int i = 0; i < self.classModelArray.count; i++) {
        
        VRCaipiaoClass *model = self.classModelArray[i];
        NSString *nameStr = model.name;
        NSString *pinyinStr = model.name.pinyin;
        
        NSRange nameRange = [nameStr rangeOfString:searchText options:searchOptions];
        NSRange pinyinRange = [pinyinStr rangeOfString:searchText options:searchOptions];
        
        if (nameRange.length || pinyinRange.length)
        {
            [self.searchResultArr addObject:model];
        }
        
    }
}


#pragma mark - delegate
#pragma mark TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.searchBar.text.length > 0) {
        return self.searchResultArr.count;
    }
    return self.classModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    VRCaipiaoClass *model = nil;
    
    if (self.searchBar.text.length > 0) {
        
        model = self.searchResultArr[indexPath.row];
    }else{
        
        model = self.classModelArray[indexPath.row];
    }
    
    VRCaipiaoClassCell *cell = [VRCaipiaoClassCell cellWith:tableView];
    cell.model = model;
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    VRCaipiaoClass *model = nil;
    
    if (self.searchBar.text.length > 0) {
        
        model = self.searchResultArr[indexPath.row];
    }else{
        
        model = self.classModelArray[indexPath.row];
    }
    
    VRCaipiaoDetailViewController *detailVc = [[VRCaipiaoDetailViewController alloc] init];
    detailVc.caipiaoid = model.caipiaoid;
    [self.navigationController pushViewController:detailVc animated:YES];
}


#pragma  mark searchController delgate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //    self.tabBarController.tabBar.hidden = YES;
    //    self.navigationController.navigationBar.hidden = YES;
    
    
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //取消
    [searchBar resignFirstResponder];
    
    //    [self.tableView reloadData];
}


- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    self.isSearched = NO;
    searchBar.text = nil;
    [self.searchResultArr removeAllObjects];
    [searchBar setShowsCancelButton:NO animated:YES];
    
    [self.tableView reloadData];
    return YES;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text.length == 0) {
        [searchBar resignFirstResponder];
        [searchBar setShowsCancelButton:NO animated:YES];
        self.isSearched = NO;
        
        //        [self.tableView reloadData];
    }else{
        
        self.isSearched = YES;
        
        //        [self getSearchResultBy:searchBar.text];
        [self filterContentForSearchText:searchBar.text];
        
        [self.tableView reloadData];
    }
    
}



@end
